package com.surelution.projects.crm
import java.text.SimpleDateFormat
import groovy.time.TimeCategory

import org.codehaus.groovy.grails.commons.ConfigurationHolder

class CardAssignController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def htmlTableParserService
	def exportService
	def ImportExcelService
	def springSecurityService
	def GasReportService
	
    def index = {
        redirect(action: "report", params: params)
    }
	
	/**
	 * 显示开卡量同比环比情况
	 */
	def report = {
		def endDayA1, endDay1
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def rList
		def areaIds = []
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			use(TimeCategory) {
				endDay1 = endDay + 1.days  
				endDayA1 = endDayA + 1.days
			}
			rList = GasReportService.cardReport(startDay,endDay1,startDayA,endDayA1,"n")
			if (!rList){
				flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
				redirect(action: "report")
			}
		}
		[list:rList,startDay:startDay,endDay:endDay,startDayA:startDayA,endDayA:endDayA]
	}
	/**
	 * 开卡计划完成量同比环比
	 */
	def planReport = {
		def endDayA1, endDay1
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def rList
		def areaIds = []
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			use(TimeCategory) {
				endDay1 = endDay + 1.days
				endDayA1 = endDayA + 1.days
			}
			rList = GasReportService.cardReport(startDay,endDay1,startDayA,endDayA1,"n")
			if (rList == 0){
				flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
				redirect(action: "planReport")
			}
		}
		[list:rList,startDay:startDay,endDay:endDay,startDayA:startDayA,endDayA:endDayA]
	}
	
	/**
	 * 导出开卡量同比环比查询
	 */
	def export = {
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel'] 
		response.setHeader("Content-disposition", "attachment; filename=cardAssign.xls")
		def endDayA1, endDay1
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def list
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			use(TimeCategory) {
				endDay1 = endDay + 1.days  
				endDayA1 = endDayA + 1.days
			}
			list = GasReportService.cardReport(startDay,endDay1,startDayA,endDayA1,"n" )
			if (!list){
				flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
				redirect(action: "report")
			}
			def mapList = new ArrayList<HashMap>()
			list.each {
				def map = new HashMap()
				map.put("stationName", it[0].shortName)
				map.put('cardSum', it[1])
				map.put('compareCardSum', it[2])
				map.put('growthRate', it[3])
				mapList.add(map)
			}
			List fields = ['stationName','cardSum','compareCardSum','growthRate']
			Map labels = ['stationName':"站名",'cardSum':"${startDay.format("MM-dd")}到${endDay.format("MM-dd")}开卡总量",'compareCardSum':"${startDayA.format("MM-dd")}到${endDayA.format("MM-dd")}开卡总量",'growthRate':"增长率%"]

		exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}
	}
	
	def planExport = {
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
		response.setHeader("Content-disposition", "attachment; filename=cardAssignPlan.xls")
		def startDay ,endDay, startDayA, endDayA, endDayA1, endDay1
		def rList
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			use(TimeCategory) {
				endDay1 = endDay + 1.days
				endDayA1 = endDayA + 1.days
			}
			rList = GasReportService.cardReport(startDay,endDay1,startDayA,endDayA1,"n" )
			if (rList == 0){
				flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
				redirect(action: "planReport")
			}
			def mapList = new ArrayList<HashMap>()
			rList.each {
				def map = new HashMap()
				map.put("stationName", it[0].shortName)
				map.put('cardSumA', it[1])
				map.put('cardPlanA', it[4])
				map.put('cardFinishA', it[6])
				map.put('cardSumB', it[2])
				map.put('cardPlanB', it[5])
				map.put('cardFinishB', it[7])
				mapList.add(map)
			}
			List fields = ['stationName','cardSumA','cardPlanA','cardFinishA','cardSumB','cardPlanB','cardFinishB']
			Map labels = ['stationName':"站名",'cardSumA':"${startDay.format("MM-dd")}到${endDay.format("MM-dd")}开卡总量",'cardSumB':"${startDayA.format("MM-dd")}到${endDayA.format("MM-dd")}开卡总量",'cardFinishA':"计划完成率",'cardFinishB':"计划完成率",'cardPlanA':"计划量",'cardPlanB':"计划量"]

		exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}
		
	}
	
	def reportAll = {
		def startDay,endDay,endDay1
		def cardAssign,result
		
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			use(TimeCategory) {
				endDay1 = endDay + 1.days
			}
			def cri = CardAssignList.createCriteria()
			cardAssign = cri.list(){
				projections{
					property("station")
					sum("personAll")
					sum("companyAll")
					sum("anonyAll") 
					sum("countAllSend")
					groupProperty("station")
				}
					lt("assignDay",endDay1)
					ge("assignDay",startDay)
			}
			
			String hql = '''select cal.station,
			sum(cal.personAll),
			sum(cal.companyAll),
			sum(cal.anonyAll),
			sum(cal.countAllSend) 
			from CardAssignList cal group by cal.station
			 order by sum(cal.countAllSend) DESC'''
			result = CardAssignList.executeQuery(hql)
		}
		if (params.startDay > params.endDay){
			flash.message = "开始时间不能大于结束时间"
		}
		[cardAssign:result,startDay:startDay,endDay:endDay]
	}
/**
 * 卡消比时间段统计显示、导出、分析
 */
	def cardAllProp = {
		def startDay = new Date()
		def endDay = new Date()
		def cardPropList
		if (params.startDay&&params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			if 	(startDay>endDay){
				flash.message = "开始时间不能大于结束时间"
				redirect(action: "cardAllProp")
			}
			cardPropList = GasReportService.cardPropReport(startDay,endDay )
			if (!cardPropList){
				flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
				redirect(action: "cardAllProp")
			}
		}
		[cardPropList:cardPropList,startDay:startDay,endDay:endDay]
	}

	def propExport = {
		def startDay,endDay
		def cardPropList
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel'] 
		response.setHeader("Content-disposition", "attachment; filename=cardAllProp.xls")
		if (params.startDay&&params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			if 	(startDay>endDay){
				flash.message = "开始时间不能大于结束时间"
				redirect(action: "cardAllProp")
			}
			cardPropList = GasReportService.cardPropReport(startDay,endDay )
			if (!cardPropList){
				flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
				redirect(action: "cardAllProp")
			}
			def mapList = new ArrayList<HashMap>()
			cardPropList.each {
				def map = new HashMap()
				map.put("stationName", it[0].shortName)
				map.put('ICAmount', it[1])
				map.put('AllAmount', it[2])
				map.put('CardPropRate', it[3])
				mapList.add(map)
			}
			List fields = ['stationName','ICAmount','AllAmount','CardPropRate']
			Map labels = ['stationName':"站名",'ICAmount':"IC卡金额(元)",'AllAmount':"总金额(元)",'CardPropRate':"卡销比(%)"]
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])			
		}
	}
	
	
/**
 * 卡消比同比环比查询显示/导出/分析
 */
	def compareCardAllProp = {
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def cardPropList
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			cardPropList = compCardPropReport(startDay,endDay,startDayA,endDayA )
		}
		[cardPropList:cardPropList,startDay:startDay,endDay:endDay,startDayA:startDayA,endDayA:endDayA]
	}

	def allPropExport = {
		def startDay,endDay,startDayA,endDayA
		def cardPropList
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
		response.setHeader("Content-disposition", "attachment; filename=AllProp.xls")
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			cardPropList = compCardPropReport(startDay,endDay,startDayA,endDayA )
			
			def mapList = new ArrayList<HashMap>()
			cardPropList.each {
				def map = new HashMap()
				map.put("stationName", it[0].name)
				map.put('ICAmount', it[1])
				map.put('AllAmount', it[2])
				map.put('CardPropRate', it[3])
				map.put('afterICAmount', it[4])
				map.put('afterAllAmount', it[5])
				map.put('afterCardPropRate', it[6])
				map.put('increase', it[7])
				mapList.add(map)
			}
			List fields = ['stationName','ICAmount','AllAmount','CardPropRate','afterICAmount','afterAllAmount','afterCardPropRate','increase']
			Map labels = ['stationName':"站名",'ICAmount':"IC卡金额(元)",'AllAmount':"总金额(元)",'CardPropRate':"卡销比(%)",'afterICAmount':"后-IC卡金额(元)",'afterAllAmount':"后-总金额(元)",'afterCardPropRate':"后-卡销比(%)",'increase':"增量(%)"]
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])
		}
	}
	
		
	def compCardPropReport(Date startDay,Date endDay,Date startDayA,Date endDayA){
		def result,cresult,cardPropList
		if 	(startDay>endDay||startDayA>endDayA){
			flash.message = "开始时间不能大于结束时间"
			redirect(action: "compareCardAllProp")
		}
		String sql = '''select gs.station,
					sum(gs.icCardAmount),
					sum(gs.actualAmount),
					sum(gs.icCardAmount),
					sum(gs.actualAmount),
					sum(gs.actualAmount),
					sum(gs.actualAmount),
					sum(gs.actualAmount) 
					from GasSale gs where gs.saleTime <= :endDay and gs.saleTime >= :startDay group by gs.station'''
		result = GasSale.executeQuery(sql,['startDay':startDay, 'endDay':endDay])
		
		String hsql = '''select gs.station,
						sum(gs.icCardAmount),
						sum(gs.actualAmount) 
						from GasSale gs where gs.saleTime <= :endDayA and gs.saleTime >= :startDayA group by gs.station'''
		cresult = GasSale.executeQuery(hsql,['startDayA':startDayA, 'endDayA':endDayA])
		if (!cresult||!result){
			flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
            redirect(action: "compareCardAllProp")
			}
		def cardProp1 = new HashMap()
		cresult.each {
			cardProp1.put(it[0], it[1])
		}
		def cardProp2 = new HashMap()
		cresult.each {
			cardProp2.put(it[0], it[2])
		}
		result.each {
			it[4] = cardProp1.get(it[0])
			it[5] = cardProp2.get(it[0])
			if (it[2]&&it[1]){
				it[3] = it[1]/it[2]*100
			}
			else it[3] = 0
			if (it[5]){
				it[6] = it[4]/it[5]*100
			}
			else it[6] = 0
			it[7] = it[3]-it[6]
		}
		result.sort {
			-it[7]
		}
		return result
	}	
	
/**
 * 沉淀资金时间段查询显示、导出、分析
 */
	def depositMoney = {
		def startDay = new Date()
		def endDay =new Date()
		def cardPropList
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			cardPropList = depositMoneyReport(startDay,endDay)
		}
		[cardPropList:cardPropList,startDay:startDay,endDay:endDay]
	}
	
	def exportDespoit = {
		def startDay,endDay
		def cardPropList
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
		response.setHeader("Content-disposition", "attachment; filename=DespoitMoney.xls")
		if (params.startDay&& params.endDay){
			startDay = params.startDay
			endDay = params.endDay
			cardPropList = depositMoneyReport(startDay,endDay)
			def mapList = new ArrayList<HashMap>()
			cardPropList.each {
				def map = new HashMap()
				map.put("stationName", it[0].name)
				map.put('tradeSum', it[1])
				map.put('rechargeSum', it[2])
				map.put('despoitMoney', it[3])
				mapList.add(map)
			}
			List fields = ['stationName','tradeSum','rechargeSum','despoitMoney']
			Map labels = ['stationName':"站名", 'tradeSum':"总消费量",'rechargeSum':"总充值量", 'despoitMoney':"沉淀资金"]
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])	
		}
		return	
	}
		
	def depositMoneyReport(Date startDay, Date endDay) {
		def result,cresult,endDay1,startDay1
		if 	(startDay>endDay){
			flash.message = "开始时间不能大于结束时间"
			redirect(action: "depositMoney")
		}
		String hsql = '''select gs.station,
					sum(gs.icCardAmount),
					sum(gs.actualAmount),
					sum(gs.actualAmount) 
					from GasSale gs where gs.saleTime <= :endDay and gs.saleTime >= :startDay group by gs.station.name'''
		result = GasSale.executeQuery(hsql,['startDay':startDay, 'endDay':endDay])
		use(TimeCategory) {
			startDay1 = startDay - 1.days + 16.hours
			endDay1 = endDay + 16.hours
		}
		String shsql = '''select gcr.station,
						sum(gcr.tradeSum)
						from GasCardRecharge gcr where gcr.tradeTime <= :endDay and gcr.tradeTime >= :startDay group by gcr.station.name'''
		cresult = GasCardRecharge.executeQuery(shsql,['startDay':startDay1, 'endDay':endDay1])
		if (!cresult||!result){
			flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
            redirect(action: "depositMoney")
			}
		def despositMoney = new HashMap()
		cresult.each {
			despositMoney.put(it[0], it[1])
		}			
		result.each {
			if (despositMoney.get(it[0])){
				it[2] = despositMoney.get(it[0])
			}
			else it[2] = 0
			it[3] = it[2]-it[1]
		}
		result.sort{
			-it[3]
		}
		return result
	}
	
/**
 * 沉淀资金同比环比显示、导出、分析	
 */
	def compareDeposit = {
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def despoitList
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			despoitList = compareDepositReport(startDay,endDay,startDayA,endDayA)
		}
		[despoitList:despoitList,startDay:startDay,endDay:endDay,startDayA:startDayA,endDayA:endDayA]
	}	
	
	def compareDespoitExport = {
		def startDay = new Date()
		def endDay = new Date()
		def startDayA = new Date()
		def endDayA = new Date()
		def despoitList
		response.contentType = ConfigurationHolder.config.grails.mime.types['excel']
		response.setHeader("Content-disposition", "attachment; filename=compareDespoit.xls")
		if (params.startDay&& params.endDay&&params.startDayA&& params.endDayA){
			startDay = params.startDay
			endDay = params.endDay
			startDayA = params.startDayA
			endDayA = params.endDayA
			despoitList = compareDepositReport(startDay,endDay,startDayA,endDayA)
			def mapList = new ArrayList<HashMap>()
			despoitList.each {
				def map = new HashMap()
				map.put("stationName", it[0].shortName)
				map.put('saleAll', it[1])
				map.put('rechargeAll', it[2])
				map.put('despoitMoney', it[3])
				map.put("AfterSaleAll", it[4])
				map.put('AfterRechargeAll', it[5])
				map.put('AftreDespoitMoney', it[6])
				map.put('rate', it[7])
				mapList.add(map)
			}
			List fields = ['stationName','saleAll','rechargeAll','despoitMoney','AfterSaleAll','AfterRechargeAll','AftreDespoitMoney','rate']
			Map labels = ['stationName':"站名", 'saleAll':"前-总消费量",'rechargeAll':"前-总充值量",'despoitMoney':"前-沉淀资金量",'AfterSaleAll':"后-总消费量 ",'AfterRechargeAll':"后-总充值量",'AftreDespoitMoney':"后-沉淀资金量",'rate':"增长率"]
			exportService.export("excel", response.outputStream, mapList, fields, labels,[:],[:])	
		}
	}
	
	
	def compareDepositReport(Date startDay, Date endDay,Date startDayA, Date endDayA) {
		def result,cresult,ccresult,cccresult,endDay1,endDayA1,startDay1,startDayA1
		use(TimeCategory) {
			startDay1 = startDay - 1.days + 16.hours
			endDay1 = endDay + 16.hours
			startDayA1 = startDayA - 1.days + 16.hours
			endDayA1 = endDayA + 16.hours
		}
		if 	(startDay>endDay||startDayA>endDayA){
			flash.message = "开始时间不能大于结束时间"
			redirect(action: "compareDeposit")
		}
		String hsql = '''select gs.station,
					sum(gs.icCardAmount),
					sum(gs.actualAmount),
					sum(gs.icCardAmount),
					sum(gs.actualAmount),				
					sum(gs.actualAmount),
					sum(gs.actualAmount),
					sum(gs.actualAmount)
					from GasSale gs where gs.saleTime <= :endDay and gs.saleTime >= :startDay group by gs.station.name'''
		result = GasSale.executeQuery(hsql,['startDay':startDay, 'endDay':endDay])
		
		String shsql = '''select gcr.station,
						sum(gcr.tradeSum)
						from GasCardRecharge gcr where gcr.tradeTime <= :endDay and gcr.tradeTime >= :startDay group by gcr.station.name'''
		cresult = GasCardRecharge.executeQuery(shsql,['startDay':startDay1, 'endDay':endDay1])
		def despositMoney = new HashMap()
		cresult.each {
			despositMoney.put(it[0], it[1])
		}
		result.each {
			if (despositMoney.get(it[0])) it[2] = despositMoney.get(it[0])
			else it[2] = 0
			it[3] = it[2]-it[1]
		}
		String chsql = '''select gs.station,
				sum(gs.icCardAmount)
				from GasSale gs where gs.saleTime <= :endDayA and gs.saleTime >= :startDayA group by gs.station.name'''
		ccresult = GasSale.executeQuery(chsql,['startDayA':startDayA, 'endDayA':endDayA])
		
		String cshsql = '''select gcr.station,
					sum(gcr.tradeSum)
					from GasCardRecharge gcr where gcr.tradeTime <= :endDayA and gcr.tradeTime >= :startDayA group by gcr.station.name'''
		cccresult = GasCardRecharge.executeQuery(cshsql,['startDayA':startDayA1, 'endDayA':endDayA1])
		if (!result||!cresult||!ccresult||!cccresult){
			flash.message = "${message(code: 'default.nofound.message', args: [message(code: 'gasList.label', default: 'GasList')])}"
			redirect(action: "compareDeposit")
		}
		def ccdespositMoney = new HashMap()
			ccresult.each {
				ccdespositMoney.put(it[0], it[1])
		}
		def cccdespositMoney = new HashMap()
			cccresult.each {
				cccdespositMoney.put(it[0], it[1])
		}
		result.each {
			if (ccdespositMoney.get(it[0])) it[4] = ccdespositMoney.get(it[0])
			else it[4] = 0
			if (cccdespositMoney.get(it[0])) it[5] = cccdespositMoney.get(it[0])
			else it[5] = 0
			it[6] = it[5]-it[4]
			it[7] = it[3]-it[6]
		}
		result.sort{
			-it[7]
		}
		return result
	}
	
	
	def cardAssignImport = {
		def fromLine =4
		def file = params.cardAssignFile
		int lineNum = 0
		
		BufferedReader br = new BufferedReader(new InputStreamReader(file.inputStream, "utf8"))
		def rows = htmlTableParserService.parse(br)
		rows.each {row->
			if(lineNum > fromLine) {
				println row
				if(row.size() > 14) {
					CardAssign cardAssign = new CardAssign("stationName":row[0],"personSend":row[1],"personRise":row[2],
						"personDestory":row[3],"personAdjustIn":row[4],"personAdjustOut":row[5],"personAll":row[6],
						"companySend":row[7],"companyDestory":row[8],"companyAdjustIn":row[9],"companyAdjustOut":row[10],"companyAll":row[11],
						"anonySend":row[12],"anonyDestory":row[13],"anonyAdjustIn":row[14],"anonyAdjustOut":row[15],"anonyAll":row[16],
						"countAllSend":row[17],"countAllDestory":row[18],)
					cardAssign.assignDay = params.assignDate
					cardAssign.save()
					
					int personAll=Integer.parseInt("${row[6]}")
					int companyAll=Integer.parseInt("${row[11]}")
					int anonyAll=Integer.parseInt("${row[16]}")
					int countAllSend=Integer.parseInt("${row[17]}")
										
					CardAssignList cardAssignList = new CardAssignList("personAll":personAll,"companyAll":companyAll,
						"anonyAll":anonyAll,"countAllSend":countAllSend,)
					cardAssignList.station = OwnStation.findByName(row[0])
					cardAssignList.assignDay = params.assignDate
					cardAssignList.save()
				}
			}
			lineNum++
		}
		redirect(action:"list")
	}
	
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [cardAssignInstanceList: CardAssign.list(params), cardAssignInstanceTotal: CardAssign.count()]
    }

    def create = {
        def cardAssignInstance = new CardAssign()
        cardAssignInstance.properties = params
        return [cardAssignInstance: cardAssignInstance]
    }

    def save = {
        def cardAssignInstance = new CardAssign(params)
        if (cardAssignInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), cardAssignInstance.id])}"
            redirect(action: "show", id: cardAssignInstance.id)
        }
        else {
            render(view: "create", model: [cardAssignInstance: cardAssignInstance])
        }
    }

    def show = {
        def cardAssignInstance = CardAssign.get(params.id)
        if (!cardAssignInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), params.id])}"
            redirect(action: "list")
        }
        else {
            [cardAssignInstance: cardAssignInstance]
        }
    }

    def edit = {
        def cardAssignInstance = CardAssign.get(params.id)
        if (!cardAssignInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [cardAssignInstance: cardAssignInstance]
        }
    }

    def update = {
        def cardAssignInstance = CardAssign.get(params.id)
        if (cardAssignInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (cardAssignInstance.version > version) {
                    
                    cardAssignInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'cardAssign.label', default: 'CardAssign')] as Object[], "Another user has updated this CardAssign while you were editing")
                    render(view: "edit", model: [cardAssignInstance: cardAssignInstance])
                    return
                }
            }
            cardAssignInstance.properties = params
            if (!cardAssignInstance.hasErrors() && cardAssignInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), cardAssignInstance.id])}"
                redirect(action: "show", id: cardAssignInstance.id)
            }
            else {
                render(view: "edit", model: [cardAssignInstance: cardAssignInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def cardAssignInstance = CardAssign.get(params.id)
        if (cardAssignInstance) {
            try {
                cardAssignInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardAssign.label', default: 'CardAssign'), params.id])}"
            redirect(action: "list")
        }
    }
}
